<template>
  <a-spin :spinning="confirmLoading">
    <div class="imgBoxWka">
      <div class="message-text" v-if="posterShow">
        正在加载中
        <div class="loading"></div>
      </div>
      <div class="imgBox" id="exportCanvas" v-if="posterShow">
        <div class="imgTop">
          <img :src="getAvatar(posterObj.image)" />
        </div>
        <div class="h6">{{ posterObj.prompt }}</div>
        <div class="5">{{ posterObj.revisedPrompt }}</div>
        <div class="imgBom">
          <div class="imgBomLef">
            <div class="imgBomLefPho">
              <img :src="getAvatarBig(posterObj.avatar)" alt="" v-if="posterObj.avatar !== null" />
              <img src="@/assets/chatlogo.jpg" alt="" v-else />

              <span>{{ posterObj.realname }}</span>
            </div>
            <div class="guanRename">{{ posterObj.guanRename }}</div>
            <div class="website">http://ai.universetime.com.cn/</div>
          </div>
          <div class="imgBomRit">
            <div class="qrcode" id="exportCanvas" ref="qrCodeUrl"></div>
            <!-- <img src="@/assets/rem.png" alt="" /> -->
          </div>
        </div>
      </div>
      <div class="copyPoster">
        <img :src="posterUrl" alt="" />
      </div>
      <div class="btmBom" v-if="!posterShow">
        <a-button @click="copyText()">复制链接</a-button>
        <a-button type="primary" class="screenPC" @click="getDownImg(posterUrl)">下载海报</a-button>
        <a-button type="primary" class="screenMobil">长按海报保存</a-button>
      </div>
    </div>
  </a-spin>
</template>

<script>
import { getFileAccessHttpUrl, getAction } from '@/api/manage'
import { referralCode, exportDis } from '@/utils/util'
import html2canvas from 'html2canvas' //html转图片
import QRCode from 'qrcodejs2'
export default {
  mixins: [],
  name: 'DisPosterForm',
  components: {},
  props: {
    posterObj: {
      type: Object,
      default: () => {},
      required: false,
    },
    normal: {
      type: Boolean,
      default: false,
      required: false,
    },
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      posterShow: true,
      model: {},
      id: '',
      posterUrl: '',
      confirmLoading: false,
    }
  },
  computed: {},
  created() {
    // this.showFlowData()
    console.log('posterObj', referralCode())
    this.posterObj.guanRename =
      process.env.VUE_APP_API_BASE_URL === 'http://ai.universetime.com.cn/jeecg-boot' ? '宇时' : '锋范'
      let path = this.$route.fullPath
    // console.log('path', path)
    let paths = path.split('/')
    let routePath = paths[paths.length - 1]
    console.log('routePath',routePath)
    var that = this
    if(routePath === 'ChatModelDraw'){
      this.$nextTick(function () {
      this.creatQrCode(referralCode())
      setTimeout(function () {
          that.exportDisCopy('exportCanvas', that.posterObj.realname)
        }, 500)
      })
    }else{
      this.$nextTick(function () {
      this.creatQrCode(this.posterObj.code)
      setTimeout(function () {
          that.exportDisCopy('exportCanvas', that.posterObj.realname)
        }, 500)
      })
    }
  
  
  },
  methods: {
    //下载图批判
    async getDownImg(data) {
      // 获取图片对象和画布对象
      const imgUrl = data
      const response = await fetch(imgUrl)
      const blob = await response.blob()
      // 创建下载链接
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = 'image.png'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      // 释放 Blob URL
      window.URL.revokeObjectURL(url)
    },
    exportDisCopy(domId, realname) {
      let dom = document.getElementById(domId)
      this.posterShow = true
      html2canvas(dom, {
        allowTaint: false, // 是否允许跨域图像污染画布
        useCORS: true, // 使用CO RS从服务器加载图像，必须为true否则img图片可能显示不出来
        dpi: window.devicePixelRatio * 4, //将分辨率提高到特定的DPI 提高四倍
        scale: 4, //按比例增加分辨率
        // x: 裁剪画布x坐标,
        // y: 裁剪画布y坐标,
      }).then((canvas) => {
        this.posterUrl = canvas.toDataURL()
        this.posterShow = false
      })
    },
    exportDis(realname) {
      exportDis('exportCanvas', realname)
    },
    creatQrCode(url) {
      new QRCode(this.$refs.qrCodeUrl, {
        text: url, // 需要转换为二维码的内容
        width: 100,
        height: 100,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H,
      })
    },
    //复制
    copyText() {
      const text = referralCode() // 要复制的文本内容
      const el = document.createElement('textarea')
      el.value = text
      document.body.appendChild(el)
      el.select()
      document.execCommand('copy')
      document.body.removeChild(el)
      this.$message.success('链接复制成功')
    },
    getAvatar(img) {
      // console.log('getFileAccessHttpUrl(this.avatar())', getFileAccessHttpUrl(img),img)
      try {
        var imgStr = img.split('.')
        var imgSplit = imgStr[0] + '-thumbnail' + '.jpg'
      } catch {}

      // console.log("splitIMG",imgSplit)
      return getFileAccessHttpUrl(imgSplit)
    },
    getAvatarBig(img) {
      return getFileAccessHttpUrl(img)
    },
    show(record) {
      // this.model = record?Object.assign({}, record):this.model;
      // this.id = record?record.id:'';
      this.visible = true
    },
    showFlowData() {
      if (this.normal === false) {
        let params = { id: this.formData.dataId }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result)
          }
        })
      }
    },
    submitForm() {
      const that = this
      console.log('model', this.model)
      return
      // 触发表单验证
      that.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                if ('该编号已存在!' == res.message) {
                  this.model.id = ''
                }
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        } else {
          return false
        }
      })
    },
    popupCallback(row) {
      this.model = Object.assign(this.model, row)
    },
  },
}
</script>
<style lang="less" scoped >
.imgBoxWka {
  overflow: hidden;
  position: relative;
  .screenMobil {
    display: none;
  }
  .copyPoster {
    width: 410px;
    margin: auto;
    img {
      width: 100%;
    }
  }
  .imgBox {
    width: 410px;
    margin: auto;
    border: 1px solid #ccc;
    padding: 10px;
    border-radius: 8px;
    position: absolute;
    top: -1000px;
    .imgTop {
      display: flex;
      justify-content: center;
      background: #f7f7f7;
      img {
        max-width: 100%;
        max-height: 370px;
      }
    }
    .h6 {
      padding: 5px;
      font-weight: bold;
    }
    .h5 {
      padding-left: 5px;
    }
    .imgBom {
      display: flex;
      justify-content: space-between;
      padding-top: 20px;
      margin-top: 20px;
      border-top: 1px dashed #ccc;
      .imgBomLef {
        .imgBomLefPho {
          img {
            width: 34px;
            height: 34px;
            border-radius: 30px;
            margin-right: 5px;
          }
        }
        .guanRename {
          font-size: 16px;
          font-weight: bold;
          margin: 5px 0;
        }
        .website {
          color: #00abff;
        }
      }
      .imgBomRit {
        background: #f7f7f7;
        padding: 10px;
      }
    }
  }
  .btmBom {
    display: flex;
    justify-content: space-between;
    width: 410px;
    margin: 10px auto;
    button {
      width: 48%;
    }
  }
}

.message-text {
  display: flex;
  align-items: center;
  justify-content: center;
  .loading {
    width: 22px;
    height: 22px;
    border: 2px solid #1890ff;
    border-top-color: transparent;
    border-radius: 50%;
    animation: rotate 0.75s linear infinite;
    float: right;
    margin-left: 4px;
  }
}

@keyframes rotate {
  to {
    transform: rotate(360deg);
  }
}

@media screen and (max-width: 767px) {
  .imgBoxWka {
    .screenPC {
      display: none;
    }
    .screenMobil {
      display: block;
    }
    .imgBox,
    .btmBom {
      width: 100%;
    }
    .copyPoster {
      width: 100%;
    }
  }
}
</style>